package com.yxt.auth.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.yxt.auth.entity.AuthToken;
import com.yxt.common.utils.cookie.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/oauth")
public class UserLoginController {


    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    private static final String GRAND_TYPE = "password";//授权模式 密码模式


    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;


    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    //todo
//    @PostMapping("/logout")
//    public com.yxt.common.utils.R logout() {
//        return com.yxt.common.utils.R.ok();
//
//    }

    @PostMapping("/logout")
    public com.yxt.common.utils.ajax.R logout() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",null,0,false);
        CookieUtil.addCookie(response,cookieDomain,"/","refreshToken",null,0,false);

        return com.yxt.common.utils.ajax.R.ok();

    }

    private void saveCookie(String token){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
    }

    private void saveCookie(String tokenName,String takenValue,int time){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/",tokenName,takenValue,time,false);
    }

}
